from django.db import models
from django.contrib.auth.models import AbstractUser
from itsdangerous import TimedJSONWebSignatureSerializer, BadData


# Create your models here.

class User(AbstractUser):
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')

    # 新增email_active字段
    # 用于记录邮箱是否激活,默认为False:未激活
    email_active = models.BooleanField(default=False,
                                       verbose_name='邮箱验证状态')

    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

    @staticmethod
    def check_verify_email_token(token):
        """
               验证token并提取user
               :param token: 用户信息签名后的结果
               :return: user, None
               """
        # 调用 itsdangerous 类,生成对象
        # 邮件验证链接有效期：一天
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,
                                                     expires_in=60 * 60 * 24)

        try:
            # 解析传入的token值,获取data
            data = serializer.loads(token)
        except BadData:
            # 如果传入的token中没有值,则报错
            return None
        else:
            # 如果有值,则获取
            user_id = data.get('user_id')
            email = data.get('email')

            # 获取值后,尝试从User表中获取对应用户
        try:
            user = User.objects.get(id=user_id,
                                    email=email)
        except User.DoesNotExist:
            return None
        else:
            return user
